package com.ruoyi.web.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.web.domain.mes.MesWorkShop;
import com.ruoyi.web.mapper.MesWorkShopMapper;
import com.ruoyi.web.utils.UtilsSetting;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Validator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MesWorkShopService {
    @Resource
    private MesWorkShopMapper mesWorkShopMapper;
    @Resource
    private Validator validator;
    @Resource
    private SysDictDataMapper sysDictDataMapper;

    /**
     * 车间管理 -- 查询
     * @Date: 2024年1月5日
     * @Auth: 张恒
     */
    public TableDataInfo getMesWorkShop(MesWorkShop mesWorkShop){
        PageHelper.startPage(mesWorkShop.getPageNum(), mesWorkShop.getPageSize());
        List<MesWorkShop> mesWorkShops = mesWorkShopMapper.selectMesWorkShop(mesWorkShop);
        List<MesWorkShop> shopArrayList = new ArrayList<>();
        // 如果筛选了科目，需要处理一下数据
        if(StringUtils.isNotBlank(mesWorkShop.getSubjectType())){
            // 循环查询到的数据
            for (MesWorkShop workShop : mesWorkShops) {
                if(StringUtils.isNotBlank(workShop.getSubjectType())){
                    // 将科目分组，然后存在筛选项的保存起来
                    String[] split = workShop.getSubjectType().split(",");
                    boolean baoHan = false;
                    for (int i = 0; i < split.length; i++) {
                        if(split[i].equals(mesWorkShop.getSubjectType())){
                            baoHan = true;
                            break;
                        }
                    }
                    if(baoHan){
                        shopArrayList.add(workShop);
                    }
                }
            }
        }else {
            shopArrayList = mesWorkShops;
        }
        PageInfo pageInfo = new PageInfo<>(shopArrayList);
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(pageInfo.getTotal());
        tableDataInfo.setRows(pageInfo.getList());
        return tableDataInfo;
    }

    /**
     * 车间管理 -- 新增
     * @Date: 2024年1月5日
     * @Auth: 张恒
     */
    public AjaxResult addMesWorkShop(MesWorkShop mesWorkShop){
        String username = SecurityUtils.getUsername();
        Date date = new Date();
        mesWorkShop.setCreateBy(username);
        mesWorkShop.setCreateTime(date);
        // 查询当月的数据
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        MesWorkShop workShop = new MesWorkShop();
        workShop.setYearTime(year);
        workShop.setMonthTime(month);
        List<MesWorkShop> mesWorkShops = mesWorkShopMapper.selectMesWorkShop(workShop);
        // 获取最大的序号
        Integer maxNum = 0;
        if(mesWorkShops.size() > 0){
            for (MesWorkShop shop : mesWorkShops) {
                if(maxNum.compareTo(shop.getCodeNum()) < 0){
                    maxNum = shop.getCodeNum();
                }
            }
        }
        maxNum = maxNum + 1;
        // 获取编码
        String code = UtilsSetting.getCode(maxNum, "CJ", date);
        mesWorkShop.setCode(code);
        BeanValidators.validateWithException(validator, mesWorkShop);
        // 新增
        mesWorkShopMapper.insertMesWorkShop(mesWorkShop);
        return AjaxResult.success(mesWorkShop);
    }

    /**
     * 车间管理 -- 修改
     * @Date: 2024年1月8日
     * @Auth: 张恒
     */
    public AjaxResult editMesWorkShop(MesWorkShop mesWorkShop){
        if(mesWorkShop.getId() == null){
            return AjaxResult.error("未获取到修改的主键");
        }
        String username = SecurityUtils.getUsername();
        Date date = new Date();
        mesWorkShop.setUpdateBy(username);
        mesWorkShop.setUpdateTime(date);
        // 查询修改的数据
        MesWorkShop workShop = new MesWorkShop();
        workShop.setId(mesWorkShop.getId());
        List<MesWorkShop> mesWorkShops = mesWorkShopMapper.selectMesWorkShop(workShop);
        // 1启用/停用时不需要校验
        if(mesWorkShop.getType() == null || mesWorkShop.getType() != 1){
            if(mesWorkShops.get(0).getStatus() == 2){
                return AjaxResult.error("请先停用后再修改");
            }
        }
        // 修改
        mesWorkShopMapper.updateMesWorkShop(mesWorkShop);
        return AjaxResult.success();
    }

    /**
     * 车间管理 -- 删除
     * @Date: 2024年1月8日
     * @Auth: 张恒
     */
    public AjaxResult delMesWorkShop( MesWorkShop mesWorkShop){
        if(mesWorkShop.getId() == null){
            return AjaxResult.error("未获取到删除的主键");
        }
        // 查询删除的数据
        MesWorkShop workShop = new MesWorkShop();
        workShop.setId(mesWorkShop.getId());
        List<MesWorkShop> mesWorkShops = mesWorkShopMapper.selectMesWorkShop(workShop);
        if(mesWorkShops.get(0).getStatus() == 2){
            return AjaxResult.error("请先停用后再删除");
        }
        // 删除
        mesWorkShopMapper.delMesWorkShop(mesWorkShop);
        return AjaxResult.success();
    }

    /**
     * 车间管理 -- 导出
     * @Date: 2024年1月8日
     * @Auth: 张恒
     */
    public AjaxResult exportMesWorkShop(MesWorkShop mesWorkShop){
        // 查询数据
        List<MesWorkShop> mesWorkShops = mesWorkShopMapper.selectMesWorkShop(mesWorkShop);
        List<MesWorkShop> shopArrayList = new ArrayList<>();
        // 如果筛选了科目，需要处理一下数据
        if(StringUtils.isNotBlank(mesWorkShop.getSubjectType())){
            // 循环查询到的数据
            for (MesWorkShop workShop : mesWorkShops) {
                if(StringUtils.isNotBlank(workShop.getSubjectType())){
                    // 将科目分组，然后存在筛选项的保存起来
                    String[] split = workShop.getSubjectType().split(",");
                    boolean baoHan = false;
                    for (int i = 0; i < split.length; i++) {
                        if(split[i].equals(mesWorkShop.getSubjectType())){
                            baoHan = true;
                            break;
                        }
                    }
                    if(baoHan){
                        shopArrayList.add(workShop);
                    }
                }
            }
        }else {
            shopArrayList = mesWorkShops;
        }
        if(shopArrayList.size() == 0){
            return AjaxResult.error("导出的数据为空");
        }
        //创建Workbook对象(excel的文档对象)
        SXSSFWorkbook swb = new SXSSFWorkbook(100);
        //建立新的sheet页
        SXSSFSheet sheet = swb.createSheet("车间信息导出");

        //标题样式
        CellStyle titleStyle = swb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        titleStyle.setFillForegroundColor((short) 67);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font font = swb.createFont();
        font.setBold(true);
        titleStyle.setFont(font);

        //单元格样式
        CellStyle cellStyle = swb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        // 设置字体
        Font cellFont = swb.createFont();
        cellStyle.setFont(cellFont);

        //【3】设置单元格样式为会计专用
        CellStyle amtStyle = swb.createCellStyle();
        amtStyle.setDataFormat(swb.createDataFormat().getFormat("_* #,##0.00_ ;_* -#,##0.00_ ;_* \"-\"??_ ;_ @_ "));//会计专用格式
        amtStyle.setAlignment(HorizontalAlignment.RIGHT);//水平居左
        amtStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        amtStyle.setBorderBottom(BorderStyle.THIN); //下边框
        amtStyle.setBorderLeft(BorderStyle.THIN);//左边框
        amtStyle.setBorderTop(BorderStyle.THIN);//上边框
        amtStyle.setBorderRight(BorderStyle.THIN);//右边框
        Font amtFont = swb.createFont();
        amtStyle.setFont(amtFont);

        //【4】创建标题行
        SXSSFRow row = sheet.createRow(0);
        row.createCell(0).setCellValue("车间编码");
        row.createCell(1).setCellValue("车间名称");
        row.createCell(2).setCellValue("印刷种类");
        row.createCell(3).setCellValue("科目");
        row.createCell(4).setCellValue("负责人");
        row.createCell(5).setCellValue("负责人电话");
        row.createCell(6).setCellValue("状态");
        row.createCell(7).setCellValue("备注");

        for (int i = 0; i <= 7; i++) {
            //设置表格列宽度为5000个字节
            sheet.setColumnWidth(i, 5000);
            //设置单元格样式
            row.getCell(i).setCellStyle(titleStyle);
        }

        // 查询字典
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("ems_workshop_print_type");// 印刷种类
        List<SysDictData> dataList = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> printTypeMap = dataList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        sysDictData.setDictType("ems_workshop_subject_type"); // 科目
        List<SysDictData> dictData = sysDictDataMapper.selectDictDataList(sysDictData);
        Map<String, String> subjectTypeMap = dictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        // 创建数据
        int i = 1;
        for (MesWorkShop workShop : shopArrayList) {
            // 科目
            StringBuffer stringBuffer = new StringBuffer();
            if(StringUtils.isNotBlank(workShop.getSubjectType())){
                String[] split = workShop.getSubjectType().split(",");
                for (int i1 = 0; i1 < split.length; i1++) {
                    stringBuffer.append(subjectTypeMap.get(split[i1]) + "；");
                }
            }
            row = sheet.createRow(i);
            row.createCell(0).setCellValue(workShop.getCode());
            row.createCell(1).setCellValue(workShop.getName());
            row.createCell(2).setCellValue(workShop.getPrintType() != null ? printTypeMap.get(workShop.getPrintType().toString()) : "");
            row.createCell(3).setCellValue(stringBuffer.toString());
            row.createCell(4).setCellValue(workShop.getChargePerson());
            row.createCell(5).setCellValue(workShop.getChargePersonTel());
            row.createCell(6).setCellValue(workShop.getStatus() == 1 ? "停用" : "启用");
            row.createCell(7).setCellValue(workShop.getRemark());
            // 设置样式
            for (int j = 0; j <= 7; j++) {
                row.getCell(j).setCellStyle(cellStyle);
            }
            i++;
        }

        OutputStream out = null;
        try {
            // 创建文件名
            String filename = UUID.randomUUID().toString() + "车间信息导出.xlsx";
            String downloadPath = RuoYiConfig.getDownloadPath() + filename;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            out = new FileOutputStream(downloadPath);
            swb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            throw new BaseException("导出Excel失败！" + e.getMessage());
        } finally {
            if (swb != null) {
                try {
                    swb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}
